#角色管理  add By Luxh

util = require("util")
dataPage = require('../services/dataPage').queryPage
sys_role = require('../models/sys_role')
SysRole = sys_role.SysRole
sys_resource = require('../models/sys_resource')
sys_user = require('../models/sys_user')
SysUser = sys_user.SysUser
common_util = require('../services/common_util')
resErr = require('./util').resErr


#角色列表
exports.role_list = (req,res) ->
  parent_id = req.param("parent_id")
  if !parent_id
    parent_id = '0'
  params = {"parent_id":parent_id}
  sorts = {_id:-1}
  dataPage SysRole,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)


#获取树形结构的角色信息
exports.role_tree = (req,res) ->
  SysRole.find {},(err,roles) ->
    if err
      resErr(res,err)
    else
      tree_data = []
      tree_data.push {id:'0', pId:'', name:"角色根节点", open:true,url:"list.html?parent_id=0",target:"rightFrame"}
      for r in roles
        tree_data.push {id:r._id,pId:r.parent_id,name:r.role_name,url:'list.html?parent_id='+r._id,target:"rightFrame"}
      res.json(tree_data)


#保存角色
exports.role_add = (req,res) ->
  role_code = common_util.trim(req.param("role_code"))
  role_name = common_util.trim(req.param("role_name"))
  if role_code == null or role_code == ""
    res.json({'flag':'error','msg':'角色编码不能为空！'})
  else if role_name == null or role_name == ""
    res.json({'flag':'error','msg':'角色名称不能为空！'})
  else
    sys_role.isRoleExist role_code,(err,count) ->
      if(err)
        res.json({'flag':'error','msg':err})
      else
        if count>0
          res.json({'flag':'error','msg':'角色编码已存在！'})
        else
          sys_role.add req,(err) ->
            if(err)
              console.error(err)
              res.json({'flag':'error','msg':err})
            else
              res.json({'flag':'success'})


#查看明细
exports.role_detail = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'success':false,'err_msg':'编码不得为空！'})
  else
    SysRole.findById _id,(err,result) ->
      if err
        resErr(res,err)
      else
        res.json(result)


#保存修改
exports.role_edit = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'flag':'error','msg':'编码不得为空！'})
  else
    role_code = common_util.trim(req.param("role_code"))
    role_name = common_util.trim(req.param("role_name"))
    if role_code == null or role_code == ""
      res.json({'flag':'error','msg':'角色编码不能为空！'})
    else if role_name == null or role_name == ""
      res.json({'flag':'error','msg':'角色名称不能为空！'})
    else
      SysRole.count {"_id":{"$ne":_id},"role_code":role_code},(err,count) ->
        if err
          resErr(res,err)
        else
          if count > 0
            res.json({'flag':'error','msg':'角色编码已存在！'})
          else
            SysRole.findById _id,(err,role) ->
              if err
                resErr(res,err)
              else
                role.role_code = req.param("role_code")
                role.role_name = req.param("role_name")
                role.role_desc = req.param("role_desc")
                role.status = req.param("status")
                role.save (err) ->
                  if err
                    console.error(err)
                    res.json('flag':'error','msg':err)
                  else
                    res.json('flag':'success')



#删除角色
exports.role_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    _id = req.param('_id')
    SysRole.count {"parent_id":_id},(err,count) ->
      if err
        resErr res,err
      else
        if count > 0
          res.json('flag':'error','msg':"该角色下有子角色，不能删除！")
        else
          SysRole.findByIdAndRemove _id,(err)->
            if err
              resErr res,err
            else
              res.json('flag':'success')


#到角色授权页面
exports.role_auth = (req,res) ->
  role_id = req.param("role_id")
  sys_resource.SysResoure.find {},(err,resourceList) ->
    if err
      resErr res,err
    else
      SysRole.findById role_id,(err,role) ->
        if err
          resErr res,err
        else
          authed_array = role.resources
          znodes = []
          for resource in resourceList
            id = resource._id
            pId = resource.res_parent
            name = resource.res_name
            checked = false
            for r in authed_array
              if id.toString()==r.res_id
                checked = true
                break
            params = {id:id,pId:pId,name:name,checked:checked}
            znodes.push params
          res.json({'znodes':znodes})


#保存对角色的授权
exports.role_auth_save = (req,res) ->
  _id = req.body.role_id
  authes = req.body.auths
  auth_array = []
  if authes != '0'
    auth_array = authes.split("#")
  SysRole.findById _id,(err,doc) ->
    if err
      res.json('flag':'error','msg':err)
    else
      doc.resources = []
      params = {}
      if auth_array != null and auth_array.length > 0
        for auth in auth_array
          json_auth = eval '('+auth+')'
          params.res_id = json_auth.res_id
          doc.resources.push params
      doc.markModified('array')
      doc.save (err) ->
        if err
          console.error(err)
          res.json('flag':'error','msg':err)
        else
          res.json('flag':'success')


#查看角色下的用户
exports.role_user_list = (req,res) ->
  role_id = req.param("role_id")
  value_array = []
  value_array.push role_id
  params = {}
  params.roles = {'$in':value_array}
  sorts = {_id:-1}
  dataPage SysUser,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)


#加入用户到角色中
exports.role_user_save = (req,res) ->
  username = common_util.trim(req.param("username"))
  role_id = common_util.trim(req.param("role_id"))
  if !role_id
    res.json({'flag':'error','msg':'编码不能为空！'})
  else if !username
    res.json({'flag':'error','msg':'用户名不能为空！'})
  else
    sys_user.isUsernameIncludeRole username,role_id,(err,count) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        if count > 0
          res.json({'flag':'error','msg':"该用户已加入，不能再添加"})
        else
          SysUser.findOne {"username":username},(err,user) ->
            if err
              res.json({'flag':'error','msg':err})
            else
              if !user
                sys_user.save req,(err) ->
                  if(err)
                    res.json({'flag':'error','msg':'保存出错！'})
                  else
                    res.json({'flag':'success'})
              else
                user.roles.push role_id
                user.markModified('array')
                user.save (err) ->
                  if err
                    res.json({'flag':'error','msg':'保存出错！'})
                  else
                    res.json({'flag':'success'})




#从角色中移出用户
exports.role_user_del = (req,res) ->
  ids = req.param("ids")
  ids_array = []
  role_id = req.param("role_id")
  if ids != ""
    ids_array = ids.split("#")
    SysUser.find {"_id":{"$in":ids_array}},(err,users) ->
      if err
        console.log err
      else
        for user in users
          user.markModified('array')
          user.roles.pull(role_id)
          user.save (err) ->
            if err
              console.log err
        res.json({'flag':'success'})





